package com.sjg.sys.codetemplate;

import com.sjg.sys.entity.SysDictionary;
import com.sjg.sys.entity.SysRole;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.lang.reflect.Field;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by fuqingjian on 2017/7/10.
 */
public class sqlTimplate {

    public static void creatListSql(Class clzz){
        Map obj=new HashMap();
        obj.put("objName",clzz.getSimpleName().replace("Sys",""));
        obj.put("tableName",upperCharToUnderLine(clzz.getSimpleName()));
        Field[] fls=clzz.getDeclaredFields();
        Field[] flps=clzz.getSuperclass().getDeclaredFields();
        Field[] fsall= Arrays.copyOf(fls,fls.length+flps.length);
        System.arraycopy(flps,0,fsall,fls.length,flps.length);
        List<Map> fields=new ArrayList<>();
        for(Field f:fsall){
            Map m=new HashMap();
            m.put("tableField",upperCharToUnderLine(f.getName()));
            m.put("entityField",f.getName());
            fields.add(m);
        }
        obj.put("fields",fields);

        Configuration cfg = new Configuration(Configuration.VERSION_2_3_23);
// 指定FreeMarker模板文件的位置
        try {
            cfg.setDirectoryForTemplateLoading(new File(sqlTimplate.class.getResource("/").getPath()));
            Template t=cfg.getTemplate("ftl/sqlList.ftl");

            try {
                t.process(obj, new OutputStreamWriter(System.out)); // 往模板里写数据
            } catch (TemplateException e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }


    }
    public static String upperCharToUnderLine(String param) {
        Pattern  p=Pattern.compile("[A-Z]");
        if(param==null ||param.equals("")){
            return "";
        }
        StringBuilder builder=new StringBuilder(param);
        Matcher mc=p.matcher(param);
        int i=0;
        while (mc.find()) {
            builder.replace(mc.start()+i, mc.end()+i, "_"+mc.group().toLowerCase());
            i++;
        }

        if('_' == builder.charAt(0)){
            builder.deleteCharAt(0);
        }
        return builder.toString();
    }

    public static void creatPagerSql(){

    }

    public static void main(String[] args) {
        creatListSql(SysRole.class);
    }
}
